<template>
  <div class="#app">
    <el-card>
      <!-- 2.1 顶部操作 -->

      <el-row :gutter="20">
        <el-col :span="8">
          <!-- 使用clearable属性即可得到一个可清空的输入框   clear	在点击由 clearable 属性生成的清空按钮时触发-->
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            class="input-with-select"
            clearable
            @clear="getList"
          >
            <template #append>
              <el-button icon="el-icon-search" @click="getList"></el-button>
            </template>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="showAddDialog">添加</el-button>
          <el-button type="primary" @click="deleteBlogs(multipleSelection)"
            >批量删除</el-button
          >
        </el-col>
      </el-row>

      <el-table
        :data="list"
        border
        stripe
        @selection-change="handleSelectionChange"
      >
        <!-- 索引列 -->
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column type="index" label="序号" width="60"></el-table-column>
        <el-table-column label="商品代码" prop="commodityCode"></el-table-column>
        <el-table-column label="商品名称" prop="commodityName"></el-table-column>
        <el-table-column label="商品类别" prop="commodityType"></el-table-column>
        <el-table-column label="价格" prop="price"></el-table-column>
        <el-table-column label="数量" prop="company"></el-table-column>
        <el-table-column label="创建时间" align="center" width="120px">
        <template slot-scope="{row}">
          <span>{{ row.createdTime | dateFormat}}</span>
        </template>
        </el-table-column>
        <el-table-column label="备注" prop="remarks"></el-table-column>
        <!-- 自定义列 -->
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="showEditDialog(scope.row.id)"
              >编辑
            </el-button>
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="removeById(scope.row.id)"
              >删除
            </el-button>
            <!-- {{scope.row}} -->
          </template>
        </el-table-column>
      </el-table>

      <!-- 2.3 分页 -->

      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-size="queryInfo.pagesize"
        :page-sizes="[5, 10, 20, 40]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 3.弹框区域 -->

    <!-- 添加框 -->
    <!-- modify -->
    <el-dialog
      title="添加"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <el-form
        :model="addForm"
        ref="addFormRef"
        :rules="addFormRules"
        label-width="100px"
      >
        <el-form-item label="商品代码" prop="commodityCode">
          <el-input v-model="addForm.commodityCode"></el-input>
        </el-form-item>

        <el-form-item label="商品名称" prop="commodityName">
          <el-input v-model="addForm.commodityName"></el-input>
        </el-form-item>

        <el-form-item label="商品类别" prop="commodityType ">
          <el-input v-model="addForm.commodityType"></el-input>
        </el-form-item>

        <el-form-item label="价格" prop="price ">
          <el-input v-model="addForm.price"></el-input>
        </el-form-item>

        <el-form-item label="数量" prop="company ">
          <el-input v-model="addForm.company"></el-input>
        </el-form-item>

        <el-form-item label="备注" prop="remarks">
          <el-input type="textarea" v-model="addForm.remarks"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="add">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑框 -->
    <!-- modify -->
    <el-dialog
      title="编辑角色"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <el-form
        :model="editForm"
        ref="editFormRef"
        :rules="editFormRules"
        label-width="100px"
      >
        <el-form-item label="商品代码" prop="commodityCode ">
          <el-input v-model="editForm.commodityCode"></el-input>
        </el-form-item>

        <el-form-item label="商品名称" prop="commodityName">
          <el-input v-model="editForm.commodityName"></el-input>
        </el-form-item>

        <el-form-item label="商品类别" prop="commodityType">
          <el-input v-model="editForm.commodityType"></el-input>
        </el-form-item>

        <el-form-item label="价格" prop="price">
          <el-input v-model="editForm.price"></el-input>
        </el-form-item>

        <el-form-item label="数量" prop="company ">
          <el-input v-model="editForm.company"></el-input>
        </el-form-item>

        <el-form-item label="备注" prop="remarks">
          <el-input type="textarea" v-model="editForm.remarks"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="update">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  fecthList,
  add,
  update,
  deleteOne,
  deleteByIds,
  getById,
} from "../../api/commodity_manage";
export default {
  data() {
    return {
      queryInfo: {
        query: "",
        pageNum: 1,
        pageCount: 10,
      },
      list: [],
      total: 0,
      addDialogVisible: false,
      adddialog: [],
      // modify
      addForm: {},
      // modify
      addFormRules: {
        commodityCode: [
          { required: true, message: "不能和为空", trigger: "blur" },
          { min: 1, max: 20, message: "长度在 1 到 20 个字符", trigger: "blur" },
        ],
        commodityName: [
          { required: true, message: "商品名称", trigger: "blur" },
          { min: 1, max: 20, message: "长度在 1 到 20 个字符", trigger: "blur" },
        ],
        commodityType: [
          { required: true, message: "不能和为空", trigger: "blur" },
          { min: 1, max: 20, message: "长度在 1 到 20 个字符", trigger: "blur" },
        ],
        price: [
          { required: true, message: "不能和为空", trigger: "blur" },
          { min: 1, max: 20, message: "长度在 1 到 20 个字符", trigger: "blur" },
        ],
        company: [
          { required: true, message: "不能和为空", trigger: "blur" },
          { min: 1, max: 20, message: "长度在 1 到 20 个字符", trigger: "blur" },
        ],
        remarks: [
          { required: true, message: "不能和为空", trigger: "blur" },
          { min: 1, max: 20, message: "长度在 1 到 20 个字符", trigger: "blur" },
        ],
      },
      editDialogVisible: false,
      // modify
      editForm: {},
      // modify
      editFormRules: {
       commodityCode: [
          { required: true, message: "不能和为空", trigger: "blur" },
          { min: 1, max: 20, message: "长度在 1 到 20 个字符", trigger: "blur" },
        ],
        commodityName: [
          { required: true, message: "商品名称", trigger: "blur" },
          { min: 1, max: 20, message: "长度在 1 到 20 个字符", trigger: "blur" },
        ],
        commodityType: [
          { required: true, message: "不能和为空", trigger: "blur" },
          { min: 1, max: 20, message: "长度在 1 到 20 个字符", trigger: "blur" },
        ],
        price: [
          { required: true, message: "不能和为空", trigger: "blur" },
          { min: 1, max: 20, message: "长度在 1 到 20 个字符", trigger: "blur" },
        ],
        company: [
          { required: true, message: "不能和为空", trigger: "blur" },
          { min: 1, max: 20, message: "长度在 1 到 20 个字符", trigger: "blur" },
        ],
        remarks: [
          { required: true, message: "不能和为空", trigger: "blur" },
          { min: 1, max: 20, message: "长度在 1 到 20 个字符", trigger: "blur" },
        ],
      },

      multipleSelection: [],
      ids: [],
    };
  },
  created() {
    this.getList();
  },
  //方法
  methods: {
    //查询  async  await
    getList() {
      //{k1:v1,k2:v2}  ---> ?k1=v1&k2=v2    query=&pagenum=1&pagesize=10
      // console.log(this.queryInfo, this.$qs.stringify(this.queryInfo));
      fecthList(this.queryInfo).then((response) => {
        this.list = response.data.records;
        this.total = response.data.total;
        setTimeout(() => {}, 1.5 * 1000);
      });
      // const { data: res } = await this.$http.post(
      //   "/dict/list",
      //   this.$qs.stringify(this.queryInfo)
      // );

      // console.log(res);

      // if (res.code !== 200) {
      //   return this.$message.error("获取列表失败！,错误信息为：" + res.msg);
      // }

      // this.list = res.data.records;

      // this.total = res.data.total;
    },

    //分页
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.queryInfo.pageCount = val;
      this.getList();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.queryInfo.pageNum = val; // 获取新页码
      this.getList();
    },

    //添加
    //弹框
    showAddDialog() {
      this.addDialogVisible = true;
    },

    add() {
      this.$refs.addFormRef.validate(async (valid) => {
        console.log(valid);

        if (!valid) return;

        console.log(this.addForm);

        add(this.addForm).then(response => {
          this.addDialogVisible = false;
          this.$notify({
            title: "成功",
            message: "添加成功",
            type: "success",
            duration: 5000,
          }); this.getList();
        });

        // console.log(res);

        // if (res.code !== 200) {
        //   return this.$message.error("添加信息失败！,错误信息为：" + res.msg);
        // }

        // this.$message.success("添加信息成功！");

        // this.addDialogVisible = false;
      });
    },

    // @close="addDialogClosed"
    addDialogClosed() {
      console.log(this.$refs); //可以获取所有带ref属性的元素
      this.$refs.addFormRef.resetFields(); //清空表单
    },

    //更新
    showEditDialog(id) {
      getById(id).then(res => {
        console.log(res.data);
        this.editForm = res.data; // 对象复制
        this.editDialogVisible = true;
      });

      // if (res.code !== 200) {
      //     return this.$message.error('查询信息失败！')
      //   }
    },
    update() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return;
        update(this.editForm).then(response => {
          const index = this.list.findIndex((v) => v.id === this.editForm.id);
          this.list.splice(index, 1, this.editForm);
          this.$notify({
            title: "修改成功",
            type: "success",
            duration: 200,
            
          });this.getList();
        });
        // 关闭对话框
        this.editDialogVisible = false;
        // 刷新数据列表
        
      });
      //
      // const {
      //   data: res
      // } = await this.$http.post(
      //   '/dict/update', this.editForm
      // )
      // if (res.code !== 200) {
      //   return this.$message.error('更新信息失败！')
      // }

      // // 提示修改成功
      // this.$message.success('更新信息成功！')
    },

    editDialogClosed() {
      this.$refs.editFormRef.resetFields();
    },
    removeById(id) {
      this.$confirm("此操作将永久删除数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          // 删除逻辑
          deleteOne(id).then(() => {
            this.$notify({
              title: "成功",
              message: "删除成功",
              type: "success",
              duration: 200,
            });
            this.getList();
          });
          // const {
          //   data: res
          // } = await this.$http.post('/dict/delete',[id])

          // if (res.code !== 200) {
          //   return this.$message.error('删除信息失败！')
          // }

          // this.$message.success('删除信息成功！')

          // this.getList()
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    handleSelectionChange(val) {
      this.multipleSelection = val;
      console.log(this.multipleSelection);
    },
    deleteBlogs(val) {
      val.forEach((element) => {
        this.ids.push(element.id);
      });
      console.log(this.ids);

      deleteByIds(this.ids).then(() => {
        this.$notify({
          title: "成功",
          message: "删除成功",
          type: "success",
          duration: 200,
        });
        this.ids = [];

        this.getList();
      });

      //   const{
      //   data: res
      // } = await this.$http.post('/dict/delete',this.ids)
      // if (res.code !== 200) {
      //       return this.$message.error('删除信息失败！')
      //     }
      //     this.$message.success('删除信息成功！')
      //     this.getList()
    },
  },
};
</script>
<style scoped>
.el-card {
  margin-top: 15px;
}

.el-table {
  margin-top: 15px;
  margin-bottom: 15px;
}
</style>
